import java.util.Arrays;

public class TestHeap {

    //存储数据
    public int[] elem;
    //存放有效数据的个数
    public int usedSize;

    public TestHeap() {
        elem = new int[10];
    }

    public void init(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void swap(int a,int b) {
        int ret = elem[a];
        elem[a] = elem[b] ;
        elem[b] = ret;
    }

    public void createHeap() {
        for (int i = (usedSize-1-1) / 2; i >= 0 ; i--) {
            siftDown(i,usedSize);
        }
    }

    public void siftDown(int parent,int k) {
        int child = 2 * parent + 1;
        while(child < k) {
            if(child + 1 < k && elem[child] < elem[child + 1]) {
                child++;
            }
            if(elem[child] > elem[parent]) {
                swap(child,parent);
                parent = child;
                child = 2 * parent + 1;
            }else {
                break;
            }
        }
    }

    public void offer(int val) {
        //容量不够则扩容
        if(isFull()) {
            elem = Arrays.copyOf(elem,2*elem.length);
        }

        elem[usedSize] = val;
        //向上调整
        siftUp(usedSize);
        usedSize++;
    }

    public void siftUp(int child) {
        int parent = (child-1) / 2;

        while(parent >= 0) {
            if(elem[child] > elem[parent]) {
                //交换
                swap(child,parent);
                child = parent;
                parent = (child-1) / 2;
            }else {
                break;
            }
        }
    }

    public boolean isFull() {
        return elem.length == usedSize;
    }

    public void poll() {
        //判断是否为空
        if(isEmpty()) {
            //抛异常
            return;
        }

        swap(0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }
}
